<template>
  <!-- 注册/编辑用户 -->
  <el-dialog class="add-store-dialog" :title="title" :visible.sync="addVisible" width="30%">
    <div class="store-body">
      <el-form ref="storeFormRef" :rules="rules" :model="storeForm" label-width="140px">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="storeForm.username" :disabled="title !== '注册用户'"></el-input>
        </el-form-item>
        <el-form-item prop="nickname" label="姓名">
          <el-input v-model="storeForm.nickname"></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="storeForm.email"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="storeForm.phone"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { mapGetters } from "vuex";
import { updateInfo, register } from "@/api/user";
import { validUsername, validUsername2 } from "@/utils/validate";
export default {
  name: "AddDialog",
  components: {},
  props: {
    visible: {
      default: false,
      type: Boolean,
    },
    storeData: {
      type: Object,
      default: {},
    },
    title: {
      type: String,
      default: "注册用户",
    },
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername2(value)) {
        callback(new Error("请输入2-10位，以大小写字母数字组成的用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("密码长度不能小于6位！"));
      } else {
        callback();
      }
    };
    //验证邮箱
    const validateEmail = (rule, value, callback) => {
      const regexp =
        /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      return regexp.test(value)
        ? callback()
        : callback(new Error("请输入正确的邮箱"));
    };
    //验证手机号
    const validatePhone = (rule, value, callback) => {
      const regexp = /^1[3-9]\d{9}$/;
      return regexp.test(value)
        ? callback()
        : callback(new Error("请输入正确的手机号"));
    };
    return {
      dialogVisible: false,
      disabled: false,
      //表单
      storeForm: {
        user_id: null,
        username: null,
        password: null,
        nickname: null,
        phone: null,
        role: 1, //用户
      },
      rules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        nickname: [{ required: true, trigger: "blur", message: "请输入姓名" }],
        email: [{ required: true, trigger: "blur", validator: validateEmail }],
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
      },
    };
  },
  watch: {},
  created() {},
  mounted() {
    if (this.title !== "注册用户") {
      this.handleEditInfo();
    }
  },
  computed: {
    ...mapGetters(["name", "token"]),
    addVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  methods: {
    cancel() {
      this.$refs.storeFormRef.resetFields();
      this.addVisible = false;
    },
    handleEditInfo() {
      this.storeForm = this.storeData;
    },
    confirm() {
      this.$refs.storeFormRef.validate(async (valid) => {
        if (valid) {
          if (this.title === "注册用户") {
            const res = await register({
              ...this.storeForm,
              password: "123456",
            });
            if (res?.status === 0) {
              this.$message.success("注册成功，默认登录密码为123456");
              this.$emit("confirm");
              this.addVisible = false;
            } else {
              this.$message.error(res.message);
            }
          } else {
            //编辑用户信息
            if (!this.storeForm?.user_id)
              return this.$message.warning("无id，请选择要编辑的信息!");
            const data = {
              ...this.storeForm,
            };
            const res = await updateInfo(data);
            if (res?.status === 0) {
              this.$message.success(res.message);
              this.$emit("confirm");
              this.addVisible = false;
            } else {
              this.$message.error(res.message);
            }
          }
        } else {
          console.log("错误提交！请重试！");
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-input {
  width: 220px;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
}
.flex-per50 {
  width: 50%;
}
</style>
